package com.southwind.controller;

import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.io.resource.UrlResource;
import com.southwind.entity.PayRecord;
import com.southwind.mapper.ParkMapper;
import com.southwind.mapper.PayRecordMapper;
import com.southwind.mapper.PropertyMapper;
import com.southwind.vo.PayRecordVO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private PayRecordMapper payRecordMapper;
    @Value("${upload.excel}")  // 读取配置中的文件路径
    private String excelFilePath;
    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private ParkMapper parkMapper;

    @PostMapping("/exportExcel")
    public void exportAllPayRecords(HttpServletResponse response) throws IOException {
        try {
            // 查询所有数据
            List<PayRecord> records = payRecordMapper.selectList(null); // 查询所有数据
            List<PayRecordVO> voList = new ArrayList<>();
            for (PayRecord record : records) {
                PayRecordVO vo = new PayRecordVO();
                BeanUtils.copyProperties(record, vo);
                vo.setPropertyName(propertyMapper.getNameById(record.getPropertyId()));
                vo.setParkName(parkMapper.getNameById(record.getParkId()));
                switch (record.getPayType()) {
                    case 1:
                        vo.setPayType("临时车");
                        break;
                    case 2:
                        vo.setPayType("包月车");
                        break;
                }
                voList.add(vo);
            }

            // 创建 Excel 文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("缴费明细");
            HSSFCellStyle style = workbook.createCellStyle();
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);

            // 写入表头
            HSSFRow headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("缴费记录ID");
            headerRow.createCell(1).setCellValue("合作名称");
            headerRow.createCell(2).setCellValue("车场名称");
            headerRow.createCell(3).setCellValue("车牌号");
            headerRow.createCell(4).setCellValue("缴费类型");
            headerRow.createCell(5).setCellValue("金额");
            headerRow.createCell(6).setCellValue("创建时间");

            // 写入数据
            int rowNum = 1;
            for (PayRecordVO vo : voList) {
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(vo.getPayRecordId());
                row.createCell(1).setCellValue(vo.getPropertyName());
                row.createCell(2).setCellValue(vo.getParkName());
                row.createCell(3).setCellValue(vo.getNumber());
                row.createCell(4).setCellValue(vo.getPayType());
                row.createCell(5).setCellValue(vo.getAmount());
                row.createCell(6).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vo.getCreateTime()));
            }

            // 设置响应头和返回流
            String fileName = "缴费明细_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.close();
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    @GetMapping("/downloadTemplate")
    public ResponseEntity<InputStreamResource> downloadTemplate() throws IOException {
        // 构造文件路径
        Path filePath = Paths.get(excelFilePath, "导入车辆信息表(模板).xls");

        // 检查文件是否存在
        FileInputStream fileInputStream = new FileInputStream(filePath.toFile());
        String encodedFileName = URLEncoder.encode("导入车辆信息表(模板).xls", StandardCharsets.UTF_8.toString());
        // 返回文件流作为响应
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+encodedFileName)

                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new InputStreamResource(fileInputStream));
    }
}
